package com.forum.model.dao;

import java.util.List;

import org.hibernate.Session;

import com.forum.model.pojo.UserMessage;
import com.forum.model.util.SessionManager;

public class UserMessageDAO implements GenericDAO<UserMessage, Long> {

	private Session session;

	@Override
	public boolean insert(UserMessage userMessage) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.save(userMessage);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public boolean update(UserMessage userMessage) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.update(userMessage);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public boolean delete(UserMessage userMessage) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.delete(userMessage);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public UserMessage getObjectById(Long id) {
		UserMessage userMessage = null;
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			userMessage = (UserMessage) session.get(UserMessage.class, id);
			session.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return userMessage;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<UserMessage> getAll() {
		List<UserMessage> all = null;

		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			all = (List<UserMessage>) session.createQuery("from UserMessage")
					.list();
			session.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}

		return all;
	}
}